package com.ruoyi.ma.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.ma.domain.*;
import com.ruoyi.ma.domain.vo.MaMaterialProgressDetailsVo;
import com.ruoyi.ma.domain.vo.MaMaterialSupplierVo;
import com.ruoyi.ma.mapper.MaMaterialPlanDetailsMapper;
import com.ruoyi.ma.mapper.MaMaterialProgressDetailsMapper;
import com.ruoyi.ma.mapper.MaMaterialSupplierMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.ma.domain.bo.MaMaterialProgressBo;
import com.ruoyi.ma.domain.vo.MaMaterialProgressVo;
import com.ruoyi.ma.mapper.MaMaterialProgressMapper;
import com.ruoyi.ma.service.IMaMaterialProgressService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 材料进度Service业务层处理
 *
 * @author llb
 * @date 2024-11-01
 */
@RequiredArgsConstructor
@Service
public class MaMaterialProgressServiceImpl implements IMaMaterialProgressService {

    private final MaMaterialProgressMapper baseMapper;
    private final MaMaterialSupplierMapper supplierMapper;
    private final MaMaterialProgressDetailsMapper progressDetailsMapper;
    private final MaMaterialPlanDetailsMapper planDetailsMapper;

    /**
     * 查询材料进度
     */
    @Override
    public MaMaterialProgressVo queryById(Long progressId){
        return baseMapper.selectVoById(progressId);
    }

    /**
     * 查询材料进度列表
     */
    @Override
    public TableDataInfo<MaMaterialProgressVo> queryPageList(MaMaterialProgressBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MaMaterialProgress> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(MaMaterialProgress::getSupplyDate);
        Page<MaMaterialProgressVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询材料进度列表
     */
    @Override
    public List<MaMaterialProgressVo> queryList(MaMaterialProgressBo bo) {
        LambdaQueryWrapper<MaMaterialProgress> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MaMaterialProgress> buildQueryWrapper(MaMaterialProgressBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MaMaterialProgress> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getBdId() != null, MaMaterialProgress::getBdId, bo.getBdId());
        lqw.eq(bo.getGysId() != null, MaMaterialProgress::getGysId, bo.getGysId());
        lqw.eq(bo.getType() != null, MaMaterialProgress::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getWaterCode()), MaMaterialProgress::getWaterCode, bo.getWaterCode());
        lqw.eq(StringUtils.isNotBlank(bo.getAcceptanceCode()), MaMaterialProgress::getAcceptanceCode, bo.getAcceptanceCode());
        lqw.eq(bo.getSupplyDate() != null, MaMaterialProgress::getSupplyDate, bo.getSupplyDate());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), MaMaterialProgress::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getContactPerson()), MaMaterialProgress::getContactPerson, bo.getContactPerson());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), MaMaterialProgress::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getRemark()), MaMaterialProgress::getRemark, bo.getRemark());
        return lqw;
    }

    /**
     * 新增材料进度
     */
    @Override
    @Transactional
    public Boolean insertByBo(MaMaterialProgressBo bo) {
        // 根据供应商id获取标段id和站点id
        LambdaQueryWrapper<MaMaterialSupplier> spLqw = Wrappers.lambdaQuery();
        spLqw.eq(bo.getGysId() != null, MaMaterialSupplier::getSupplierId, bo.getGysId());
        MaMaterialSupplierVo supplierVo = supplierMapper.getById(bo.getGysId());
        bo.setBdId(supplierVo.getBdId());
        bo.setZdId(supplierVo.getZdId());
        // 保存主表
        MaMaterialProgress add = BeanUtil.toBean(bo, MaMaterialProgress.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setProgressId(add.getProgressId());
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 保存子表
        List<MaMaterialProgressDetails> detailList = bo.getDetailList();
        detailList.forEach(item -> {
            try {
                Date date = sdf.parse(bo.getSupplyDate());
                item.setSupplyDate(date);
                item.setAcceptanceCode(bo.getAcceptanceCode());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            item.setProgressId(bo.getProgressId());
        });
        return progressDetailsMapper.insertBatch(detailList);
    }

    /**
     * 修改材料进度
     */
    @Override
    @Transactional
    public Boolean updateByBo(MaMaterialProgressBo bo) {
        // 更新主表
        MaMaterialProgress update = BeanUtil.toBean(bo, MaMaterialProgress.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            // 更新子表
            List<MaMaterialProgressDetails> detailList = bo.getDetailList();
            detailList.forEach(item -> {
                item.setSupplyDate(update.getSupplyDate());
                item.setAcceptanceCode(update.getAcceptanceCode());
            });
            return progressDetailsMapper.updateBatchById(detailList);
        } else {
            return false;
        }
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MaMaterialProgress entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除材料进度
     */
    @Override
    @Transactional
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        // 删除主表
        boolean flag = baseMapper.deleteBatchIds(ids) > 0;
        if (flag) {
            // 删除子表
            ids.forEach(progressId -> {
                LambdaQueryWrapper<MaMaterialProgressDetails> lqw = Wrappers.lambdaQuery();
                lqw.eq(progressId != null, MaMaterialProgressDetails::getProgressId, progressId);
                List<MaMaterialProgressDetails> detailsList = progressDetailsMapper.selectList(lqw);
                progressDetailsMapper.deleteBatchIds(detailsList);
            });
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取材料进度主表和子表信息
     *
     * @param progressId
     * @return
     */
    @Override
    public MaMaterialProgressBo infoData(Long progressId) {
        // 查询主表
        MaMaterialProgress entity = baseMapper.selectById(progressId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(entity.getSupplyDate());
        MaMaterialProgressBo data = BeanUtil.copyProperties(entity, MaMaterialProgressBo.class);
        data.setSupplyDate(date);
        // 查询子表
//        LambdaQueryWrapper<MaMaterialProgressDetails> lqw = Wrappers.lambdaQuery();
//        lqw.eq(progressId != null, MaMaterialProgressDetails::getProgressId, progressId);
//        List<MaMaterialProgressDetails> detailList = progressDetailsMapper.selectList(lqw);
        handleMonthTotalSupplyNumber(progressId, entity.getGysId());
        List<MaMaterialProgressDetails> detailList = handleMonthPlanPurchaseNumber(progressId, entity.getGysId());
        data.setDetailList(detailList);
        return data;
    }

    // 处理本月计划采购数量
    @Transactional
    public List<MaMaterialProgressDetails> handleMonthPlanPurchaseNumber(Long progressId, Long gysId) {
        // 获取签收对应的计划详情
        List<MaMaterialPlanDetails> planDetails = planDetailsMapper.getProgressPlanDetails(progressId, gysId);
        // 获取签收明细
        LambdaQueryWrapper<MaMaterialProgressDetails> lqw = Wrappers.lambdaQuery();
        lqw.eq(progressId != null, MaMaterialProgressDetails::getProgressId, progressId);
        List<MaMaterialProgressDetails> detailList = progressDetailsMapper.selectList(lqw);
        detailList.forEach(item -> {
            Optional<MaMaterialPlanDetails> first = planDetails.stream().filter(o -> o.getManifestId().equals(item.getManifestId())).findFirst();
            if (first.isPresent()) {
                MaMaterialPlanDetails plan = first.get();
                item.setMonthPlanPurchaseNumber(plan.getMonthPurchaseNumber());
            } else {
                item.setMonthPlanPurchaseNumber(BigDecimal.ZERO);
            }
        });
        progressDetailsMapper.updateBatchById(detailList);
        return detailList;
    }

    // 处理本月累计供应数量
    @Transactional
    public void handleMonthTotalSupplyNumber(Long progressId, Long gysId) {
        // 获取当月签收明细
        List<MaMaterialProgressDetails> monthDetails = progressDetailsMapper.getMonthDetails(progressId, gysId);
        Map<Long, List<MaMaterialProgressDetails>> map = monthDetails.stream().collect(Collectors.groupingBy(MaMaterialProgressDetails::getManifestId));
        map.entrySet().forEach(item -> {
            Long manifestId = item.getKey();
            List<MaMaterialProgressDetails> list = item.getValue();
            List<BigDecimal> onceSupplyNumberList = list.stream().map(MaMaterialProgressDetails::getOnceSupplyNumber).collect(Collectors.toList());
            BigDecimal sum = onceSupplyNumberList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
            list.forEach(bean -> {
                bean.setMonthTotalSupplyNumber(sum);
            });
            progressDetailsMapper.updateBatchById(list);
        });

    }
}
